package com.eipc;

import java.util.ArrayList;

import org.androidpn.sdk.Constants;
import org.androidpn.sdk.XmppManager;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.eipc.event.OnBarClickListener;
import com.eipc.model.Player;
import com.eipc.model.PlayerGroup;
import com.eipc.model.SerInfoResponse;
import com.eipc.model.TPlayer;
import com.eipc.util.DBHelper;
import com.eipc.util.HttpManager;
import com.eipc.util.MyLog;

/**
 * 选手档案(单打选手或双打选手)
 * @author x_liaolijun
 *
 * 2010-9-12 上午08:46:12
 *  
 * PlayerRecordActivity
 *
 */
public class PlayerRecordActivity2 extends CommonActivity {
	private ListView mListView;
	private int type ;   //单打还是双打(默认为单打)
	private AlertDialog.Builder mBuilder;
	private LoadPlayersTask mTask;
	public boolean isNotRef = true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player_record2);
		type = PlayerRecordActivity.TYPE_SINGLE;
		Intent i = getIntent();
		if(i!=null){
			type = i.getIntExtra("type", PlayerRecordActivity.TYPE_SINGLE);	
		}
		initView();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			setResult(RESULT_OK);
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 弹出框
	 * @param playerId
	 */
	
	@Override
	protected void initView() {
		mBuilder = new Builder(this).setTitle(R.string.tip);
		super.initView();
		mBar.setMiddleText(R.string.player_record); 
		mBar.setOnBarClickListener(new OnBarClickListener() {
			
			@Override
			public void onClickRight() {
				if(isNotRef){
					mTask = new LoadPlayersTask();
					mTask.execute();
				}
			}
			
			@Override
			public void onClickLeft() {
				Intent i = new Intent(PlayerRecordActivity2.this, MainActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(i);
				finish();
			}
		});
		mListView = (ListView)findViewById(R.id.list1);
		Log.d("-----------------", ""+type);
		if(type == PlayerRecordActivity.TYPE_SINGLE)
			mListView.setAdapter(new PlayerAdaper(mDB.getSinglePlayer()));
		else
			mListView.setAdapter(new PlayerAdaper(mDB.getDoublePlayer()));
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	class PlayerAdaper extends BaseAdapter{
		private ArrayList<TPlayer> players;
		private TPlayer player;
		public PlayerAdaper(ArrayList<TPlayer> players){
			this.players = players;
		}

		@Override
		public int getCount() {
			if(players==null) return 0;
			return players.size();
		}

		@Override
		public Object getItem(int position) {
			return players.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			View view = null;
			TextView tv = null;
			try {
				player = players.get(position);
				if(type == PlayerRecordActivity.TYPE_SINGLE){
					view = mInflater.inflate(R.layout.player_record_item, null);			
				}
				else{
					view = mInflater.inflate(R.layout.player_record_item2, null);
				}
				tv = (TextView)view.findViewById(R.id.text1);
				tv.setText(player.rank);
				tv = (TextView)view.findViewById(R.id.text2);
				if(mLocale == LANGUAGE_CHINESE)
					tv.setText(player.playerA.enSname);
				else
					tv.setText(player.playerA.enSname);
				tv.setTag(player.playerA);
				tv.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						showPlayerDialog((Player)v.getTag());
					}
				});
				tv = (TextView)view.findViewById(R.id.text3);
				if(mLocale == LANGUAGE_CHINESE)
					tv.setText(player.playerA.enCountry);
				else
					tv.setText(player.playerA.enCountry);
				if(type == PlayerRecordActivity.TYPE_DOUBLE){
					tv = (TextView)view.findViewById(R.id.text4);
					if(mLocale == LANGUAGE_CHINESE)
						tv.setText(player.playerB.enSname);
					else
						tv.setText(player.playerB.enSname);
					tv.setTag(player.playerB);
					tv.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							showPlayerDialog((Player)v.getTag());
						}
					});
					tv = (TextView)view.findViewById(R.id.text5);
					if(mLocale == LANGUAGE_CHINESE)
						tv.setText(player.playerB.enCountry);
					else
						tv.setText(player.playerB.enCountry);
				}
				if(position%2==0){
					view.setBackgroundResource(android.R.color.white);
				}
				else{
					view.setBackgroundResource(R.drawable.player);
				}
			} catch (Exception e) {
			}
			return view;
		}
		
	}
	
	class LoadPlayersTask extends CommonTask<Void>{
		private SerInfoResponse playerSir;
		private SerInfoResponse playerGroupSir;
		private boolean isOk = false;
		
		public LoadPlayersTask(){
			super(PlayerRecordActivity2.this);
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			//TODO 删除数据
			mDB.deleteAll(DBHelper.TB_MATCH);
			mDB.deleteAll(DBHelper.TB_SCORE);
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			isNotRef = false;
			Log.i("--"+this.getClass().getName(),"------------------PollingMatchScoreTask------------------ right : ");
			try {
				SharedPreferences sdkPreferences = getSharedPreferences(Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
				String mobileID = sdkPreferences.getString(Constants.XMPP_USERNAME,"");
				playerSir = HttpManager.loadSerInfo(getString(R.string.url_load_serinfo),mobileID,mDB.GetPlayerSql(),Constants.LOAD_MODEL_PLAYER);
				playerGroupSir = HttpManager.loadSerInfo(getString(R.string.url_load_serinfo),mobileID,mDB.GetPlayerGroupSql(),Constants.LOAD_MODEL_PLAYERGROUP);
				if(playerSir!=null&&playerGroupSir!=null){
					//TODO 刷新成功 等待 PUSH	
					try{mDB.savePlayers((Player[])playerSir.os);}catch(Exception e){mBuilder.setMessage(R.string.status_save_player_failed).setNegativeButton(R.string.btn_close, null).show();}
					try{mDB.savePlayerGroups((PlayerGroup[])playerGroupSir.os);}catch(Exception e){mBuilder.setMessage(R.string.status_save_player_group_failed).setNegativeButton(R.string.btn_close, null).show();}
					isOk = true;
				}
			} catch (Exception e) {
				MyLog.error(FetchConsultService.class,"",e);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			isNotRef = true;
			if(!isOk){
				mBuilder.setMessage(R.string.status_connect_failed).setNegativeButton(R.string.btn_close, null).show();
				Log.e(this.getClass().getName()+" polling failure : ","mResult is null");
			}else{
				updateView();
			}
		}
		
	}
	
	@Override
    protected void updateView(){
    	super.updateView();
    	if(mTask!=null&&!mTask.isCancelled()){
    		mTask.cancel(true);
    	}
    	Intent i = new Intent(PlayerRecordActivity2.this,PlayerRecordActivity2.class);
		startActivity(i);
		finish();
    }
}
